package com.example.writting.ui.cases

import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.UnderlineSpan
import android.text.style.StyleSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.data.cases.Case1
import org.json.JSONObject
import java.lang.StringBuilder

class CasesFragment : Fragment() {

    private lateinit var recyclerView: RecyclerView
    private lateinit var detailContainer: View
    private lateinit var caseTitle: TextView
    private lateinit var caseSource: TextView
    private lateinit var materialsContainer: ViewGroup
    private lateinit var caseQuestion: TextView
    private lateinit var answersContainer: ViewGroup

    private val casesMap = mutableMapOf<String, JSONObject>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_cases, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView = view.findViewById(R.id.casesRecyclerView)
        detailContainer = view.findViewById(R.id.detailContainer)
        caseTitle = view.findViewById(R.id.caseTitle)
        caseSource = view.findViewById(R.id.caseSource)
        materialsContainer = view.findViewById(R.id.materialsContainer)
        caseQuestion = view.findViewById(R.id.caseQuestion)
        answersContainer = view.findViewById(R.id.answersContainer)

        setupRecyclerView()
    }

    private fun setupRecyclerView() {
        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = CaseAdapter { caseId ->
            casesMap[caseId]?.let { showCaseDetail(it) }
        }
        recyclerView.adapter = adapter

        // Load cases
        val case1 = Case1.data
        casesMap["1"] = case1
        val caseItems = listOf(
            CaseItem(
                id = "1",
                title = case1.getString("title"),
                source = case1.getString("source")
            )
        )
        adapter.submitList(caseItems)
    }

    private fun formatText(text: String): SpannableString {
        val result = StringBuilder()
        val spans = mutableListOf<Pair<Int, Int>>()
        val underlines = mutableListOf<Pair<Int, Int>>()
        
        var i = 0
        while (i < text.length) {
            when {
                // Handle bold text (**text**)
                text.startsWith("**", i) -> {
                    val endIndex = text.indexOf("**", i + 2)
                    if (endIndex != -1) {
                        val startPos = result.length
                        result.append(text.substring(i + 2, endIndex))
                        spans.add(Pair(startPos, result.length))
                        i = endIndex + 2
                    } else {
                        result.append(text[i])
                        i++
                    }
                }
                // Handle underline text (==text==)
                text.startsWith("==", i) -> {
                    val endIndex = text.indexOf("==", i + 2)
                    if (endIndex != -1) {
                        val startPos = result.length
                        result.append(text.substring(i + 2, endIndex))
                        underlines.add(Pair(startPos, result.length))
                        i = endIndex + 2
                    } else {
                        result.append(text[i])
                        i++
                    }
                }
                else -> {
                    result.append(text[i])
                    i++
                }
            }
        }

        val spannable = SpannableString(result)
        
        // Apply bold spans
        spans.forEach { (start, end) ->
            spannable.setSpan(
                StyleSpan(android.graphics.Typeface.BOLD),
                start,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        
        // Apply underline spans
        underlines.forEach { (start, end) ->
            spannable.setSpan(
                UnderlineSpan(),
                start,
                end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }

        return spannable
    }

    private fun showCaseDetail(case: JSONObject) {
        try {
            recyclerView.visibility = View.GONE
            detailContainer.visibility = View.VISIBLE

            caseTitle.text = formatText(case.getString("title"))
            caseSource.text = formatText(case.getString("source"))

            // Clear previous materials
            materialsContainer.removeAllViews()

            // Add materials
            val contentArray = case.getJSONArray("content")
            for (i in 0 until contentArray.length()) {
                val material = contentArray.getJSONObject(i)
                val materialView = LayoutInflater.from(context).inflate(
                    R.layout.item_material,
                    materialsContainer,
                    false
                ) as ViewGroup

                val titleView = materialView.findViewById<TextView>(R.id.materialTitle)
                val textView = materialView.findViewById<TextView>(R.id.materialText)

                titleView.text = formatText(material.getString("title"))
                textView.text = formatText(material.getString("text"))

                // Add click listener to toggle visibility
                titleView.setOnClickListener {
                    textView.visibility = if (textView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
                }

                materialsContainer.addView(materialView)
            }

            caseQuestion.text = formatText(case.getString("question"))

            // Clear previous answers
            answersContainer.removeAllViews()

            // Add answers
            val answersArray = case.getJSONArray("answers")
            for (i in 0 until answersArray.length()) {
                val answer = answersArray.getJSONObject(i)
                val answerView = LayoutInflater.from(context).inflate(
                    R.layout.item_answer,
                    answersContainer,
                    false
                ) as ViewGroup

                val titleView = answerView.findViewById<TextView>(R.id.answerTitle)
                val textView = answerView.findViewById<TextView>(R.id.answerText)

                titleView.text = formatText(answer.getString("title"))
                textView.text = formatText(answer.getString("content"))

                // Add click listener to toggle visibility
                titleView.setOnClickListener {
                    textView.visibility = if (textView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
                }

                answersContainer.addView(answerView)
            }

        } catch (e: Exception) {
            Log.e("CasesFragment", "Error showing case detail", e)
        }
    }
} 